package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.*;
import cc.rengu.igas.bsps.common.dao.impl.*;
import cc.rengu.igas.bsps.common.entity.*;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.BankManagerService;
import cc.rengu.igas.bsps.facade.bean.InspectMchntInfoBean;
import cc.rengu.igas.bsps.facade.request.NeedInspectMchntListQueryRequest;
import cc.rengu.igas.bsps.facade.response.NeedInspectMchntListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/08
 */
public class NeedInspectMchntListQueryService extends BankManagerService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        NeedInspectMchntListQueryRequest needInspectMchntListQueryRequest = new NeedInspectMchntListQueryRequest();
        ConvertUtil.convertOutput(needInspectMchntListQueryRequest);
        return needInspectMchntListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        NeedInspectMchntListQueryRequest needInspectMchntListQueryRequest = (NeedInspectMchntListQueryRequest) request;
        NeedInspectMchntListQueryResponse needInspectMchntListQueryResponse = new NeedInspectMchntListQueryResponse();
        /*获取请求参数：法人行号，用户标识，拓展经理工号，巡检方式，巡检状态，开始日期，截止日期，当前页，当前页显示记录*/
        String instId = needInspectMchntListQueryRequest.getHeader().getInstId();
        String userId = needInspectMchntListQueryRequest.getUserId();
        String managerId = needInspectMchntListQueryRequest.getManagerId();
        String inspectType = needInspectMchntListQueryRequest.getInspectType();
        String inspectStatus = needInspectMchntListQueryRequest.getInspectStatus();
        String startDate = needInspectMchntListQueryRequest.getStartDate();
        String endDate = needInspectMchntListQueryRequest.getEndDate();
        int pageIndex = needInspectMchntListQueryRequest.getPageIndex();
        int pageSize = needInspectMchntListQueryRequest.getPageSize();
        if (0 > pageIndex) {
            pageIndex = 0;
        }
        if (0 > pageSize) {
            pageSize = 10;
        }
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(managerId) || StringUtil.isEmptyOrNull(inspectStatus)
                || StringUtil.isEmptyOrNull(startDate) || StringUtil.isEmptyOrNull(endDate)) {
            rglog.error("巡检商户列表信息查询请求参数必填校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        if (StringUtil.isEmptyOrNull(inspectType) && !"10".equals(inspectStatus)) {
            rglog.error("巡检商户列表信息查询请求参数必填校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        startDate = DateUtil.dateStringFormatConvert(startDate, "yyyyMMdd", "yyyy-MM-dd");
        endDate = DateUtil.dateStringFormatConvert(endDate, "yyyyMMdd", "yyyy-MM-dd");
        /*根据拓展经理工号查询巡检任务详情列表信息*/
        BspsInspectTaskDetailMapper bspsInspectTaskDetailMapper = new BspsInspectTaskDetailMapperImpl();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(pageSize);
        InspectTaskDetail inspectTaskDetail = new InspectTaskDetail();
        inspectTaskDetail.setInstId(instId);
        inspectTaskDetail.setManagerId(managerId);
        inspectTaskDetail.setInspectType(inspectType);
        inspectTaskDetail.setInspectStatus(inspectStatus);
        inspectTaskDetail.setInspectBeginTime(startDate);
        inspectTaskDetail.setInspectEndTime(endDate);
        PageResult inspectTaskDetailPage = bspsInspectTaskDetailMapper.selectBspsInspectDetailByManagerId(instId, inspectTaskDetail, pageInfo);
        List<InspectMchntInfoBean> inspectMchntInfoList = new ArrayList<>();
        if (null != inspectTaskDetailPage) {
            List<InspectTaskDetail> inspectTaskDetailList = inspectTaskDetailPage.getResult().stream().map(item -> (InspectTaskDetail) item).collect(Collectors.toList());
            pageInfo = inspectTaskDetailPage.getPageInfo();
            needInspectMchntListQueryResponse.setTotalPage(pageInfo.getTotalPage());
            needInspectMchntListQueryResponse.setTotalRows(pageInfo.getTotalRows());
            needInspectMchntListQueryResponse.setPageIndex(pageInfo.getPageIndex());
            needInspectMchntListQueryResponse.setPageSize(pageInfo.getPageSize());
            /* 根据查询结果组装应答报文 */
            if (null != inspectTaskDetailList && !inspectTaskDetailList.isEmpty()) {
                /* 按照截止时间降序排序 */
                List<InspectTaskDetail> inspectTaskDetails = inspectTaskDetailList.stream().sorted(Comparator.comparing(InspectTaskDetail::getInspectEndTime)).collect(Collectors.toList());
                Collections.reverse(inspectTaskDetails);
                inspectTaskDetails.forEach(item -> convInspectMchntInfo(item, inspectMchntInfoList));
            }
        }
        needInspectMchntListQueryResponse.setInspectMchntInfoList(inspectMchntInfoList);
        /* 按照接口转换基础产品信息并响应给请求方 */
        BizResponse<NeedInspectMchntListQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(needInspectMchntListQueryResponse);
        return bizResponse;
    }

    /**
     * 巡检商户详情信息转换
     * inspectTaskDetail 巡检商户详情
     */
    private void convInspectMchntInfo(InspectTaskDetail inspectTaskDetail, List<InspectMchntInfoBean> inspectMchntInfoList) {
        try {
            InspectMchntInfoBean inspectMchntInfo = new InspectMchntInfoBean();
            /*已有信息复制*/
            BeanUtil.beanCopy(inspectTaskDetail, inspectMchntInfo);
            /*根据巡检任务编号查询巡检任务名称*/
            BspsInspectTaskInfoMapper BspsInspectTaskInfoMapper = new BspsInspectTaskInfoMapperImpl();
            InspectTaskInfo inspectTaskInfo = BspsInspectTaskInfoMapper.selectBspsInspectTaskInfofoByInspectTaskNo(inspectTaskDetail.getInstId(), inspectTaskDetail.getInspectTaskNo());
            if (null != inspectTaskInfo) {
                inspectMchntInfo.setInspectTaskDesc(inspectTaskInfo.getInspectTaskDesc());
            }
            /*查询商户联系人信息*/
            BspsMchntBaseInfoMapper bspsMchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
            MchntBaseInfo mchntBaseInfo = bspsMchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(inspectTaskDetail.getInstId(), inspectTaskDetail.getMchntNo());
            if (null != mchntBaseInfo) {
                inspectMchntInfo.setMchntContactName(mchntBaseInfo.getMchntContactName());
                inspectMchntInfo.setMchntContactPhone(mchntBaseInfo.getMchntContactMobile());
                inspectMchntInfo.setMchntContactAddr(mchntBaseInfo.getMchntBizAddr());
            }
            /*查询巡检机构名称：1-巡检机构是行方机构 2-巡检机构是代理机构*/
            /*先通过组织表查询巡检机构*/
            OrganizationMapper organizationMapper = new OrganizationMapperImpl();
            Organization organization = organizationMapper.getOrganizationByOrgCode(inspectTaskDetail.getInspectInstId());
            if (null != organization) {
                inspectMchntInfo.setInspectInstName(organization.getOrgName());
            } else {
                /*2:查询代理机构信息表*/
                BspsAgentInfoMapper bspsAgentInfoMapper = new BspsAgentInfoMapperImpl();
                AgentInfo agentInfo = bspsAgentInfoMapper.selectBspsAgentInfoByInstIdAndAgentCode(inspectTaskDetail.getInstId(), inspectTaskDetail.getInspectInstId());
                if (null != agentInfo) {
                    inspectMchntInfo.setInspectInstName(agentInfo.getAgentName());
                }
            }
            inspectMchntInfoList.add(inspectMchntInfo);
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("商户列表查询详细信息转换失败:{}", byteArrayOutputStream.toString());
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        NeedInspectMchntListQueryResponse needInspectMchntListQueryResponse = (NeedInspectMchntListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(needInspectMchntListQueryResponse);
    }
}
